package com.freight.msg.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.UserRoleService;
import com.freight.core.service.UserService;
import com.freight.msg.dao.MsgCustCategoeryDao;
import com.freight.msg.dao.MsgCustMessDao;
import com.freight.msg.dto.MsgCustCategoryDto;
import com.freight.msg.dto.MsgCustMessDto;
import com.freight.msg.dto.MsgCustMessReplayDto;
import com.freight.msg.dto.MsgCustMessSaveDto;
import com.freight.msg.entity.MsgCustCategory;
import com.freight.msg.entity.MsgCustMess;
import com.freight.msg.service.MsgCustMessService;
import com.freight.msg.vo.MsgCustMessVo;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.persistence.criteria.*;
import java.io.*;
import java.util.*;

/**
 * 咨询与投诉自助问答详细信息
 *
 * @author huyingtai
 */
@Slf4j
@Service
@Transactional
public class MsgCustMessServiceImpl implements MsgCustMessService {

    @Autowired
    private MsgCustMessDao msgCustMessDao;

    @Autowired
    private MsgCustCategoeryDao msgCustCategoeryDao;

    @Autowired
    private MsgCustMessService msgCustMessService;

    @Override
    public MsgCustMessDao getRepository() {
        return msgCustMessDao;
    }

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    UserService userService;

    @Autowired
    SecurityUtil securityUtil;

    @Value("${file-save-path}")
    private String fileSavePath;

    @Override
    public MsgCustMessVo getMsgCustMessId(Long id) {

        MsgCustMessVo msgCustMessVo=new MsgCustMessVo();
        if (id!=null && id>0){
            MsgCustMess msgCustMess=msgCustMessDao.getOne(id);
            if (msgCustMess!=null&&msgCustMess.getId()!=null) {
                String newFileName = msgCustMess.getReplayMess().substring(15, 24);
                File newFile = new File(fileSavePath + newFileName);
                BufferedReader reader = null;
                StringBuffer sbf = new StringBuffer();
                try {
                    reader = new BufferedReader(new FileReader(newFile));
                    String tempStr;
                    while ((tempStr = reader.readLine()) != null) {
                        sbf.append(tempStr);
                    }
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                msgCustMessVo.setContent(sbf.toString());
                msgCustMessVo.setId(msgCustMess.getId());
                msgCustMessVo.setMsgCustCategoryId(msgCustMess.getMsgCustCategoryId());
                msgCustMessVo.setCustMess(msgCustMess.getCustMess());
                msgCustMessVo.setReplayMess(msgCustMess.getReplayMess());

            }
        }else {
            throw new FreightException("参数错误");
        }

        return msgCustMessVo;
    }

    @Override
    public void deleteMsgCustCategory(Long msgCustCategoryId) {
        List<MsgCustMess> list= msgCustMessDao.findAll(new Specification<MsgCustMess>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<MsgCustMess> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                Path<Long> msgCustCategoryId = root.get("msgCustCategoryId");
                List<Predicate> list = new ArrayList<>();

                list.add(cb.equal(msgCustCategoryId, msgCustCategoryId));

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                cq.orderBy(cb.desc(root.get("createTime")));
                return null;
            }
        });
        if (list!=null && list.size()!=0){
//            for (MsgCustMess msgCustMess:list){
//                msgCustMessDao.deleteById(msgCustMess.getId());
                msgCustMessDao.deleteAll(list);
//            }
        }
        msgCustCategoeryDao.deleteById(msgCustCategoryId);

    }

    @Override
    public void deleteMsgCustMess(Long msgCustMessId) {
        msgCustMessDao.deleteById(msgCustMessId);
    }

    @Override
    public void saveMsgCustMess(String content) {
        MsgCustMess msgCustMess;

        JSONObject json=JSONObject.parseObject(content);
        String fileName=Math.round((Math.random()+1) * 1000)+"";

        Long id=json.getLong("id");
        String custMess=json.getString("custMess");
        String replayMess=json.getString("replayMess");
        Integer sort=json.getInteger("sort");
        Long msgCustCategoryId=json.getLong("msgCustCategoryId");
        replayMess="<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body>"+replayMess+"</body></html>";
        if(id!=null && id > 0){
            msgCustMess=msgCustMessDao.getOne(id);
            if (msgCustMess!=null){
                fileName=msgCustMess.getReplayMess().substring(15,19);
            }
        }else {
            msgCustMess=new MsgCustMess();
        }

        msgCustMess.setCustMess(custMess);
        msgCustMess.setSort(sort);
        msgCustMess.setMsgCustCategoryId(msgCustCategoryId);

        String newFileName= fileName+".html";
        File newFile = new File(fileSavePath + newFileName);

        msgCustMess.setReplayMess("/platformrules/"+newFileName);

        try {
            PrintStream ps = new PrintStream(new FileOutputStream(newFile));
            ps.println(replayMess);// 往文件里写入字符串
        } catch (IOException e) {
            //"IO异常！"
        }

        msgCustMessDao.save(msgCustMess);
    }

    @Override
    public void saveMsgCustCategory(MsgCustCategoryDto msgCustCategoryDto) {
        MsgCustCategory msgCustCategory=new MsgCustCategory();
        ObjectUtil.copyPropertiesIgnoreNull(msgCustCategoryDto, msgCustCategory);
        msgCustCategoeryDao.save(msgCustCategory);
    }

    @Override
    public Page<MsgCustCategory> getMsgCustCategoryList(Pageable pageable) {

        User u = securityUtil.getCurrUser();

        Page<MsgCustCategory> res = msgCustCategoeryDao.findAll(new Specification<MsgCustCategory>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<MsgCustCategory> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();

                Predicate p1 = cb.equal(root.get("categoryType"), 3);
                Predicate p2 = cb.equal(root.get("categoryType"), u.getUserType());
                list.add(cb.or(p1, p2));

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                cq.orderBy(cb.asc(root.get("createTime")));
                return null;
            }
        }, pageable);

        return res;
    }

    @Override
    public Page<MsgCustCategory> platformMsgCustCategoryList(Pageable pageable) {

        User u = securityUtil.getCurrUser();

        Page<MsgCustCategory> res = msgCustCategoeryDao.findAll(new Specification<MsgCustCategory>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<MsgCustCategory> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                cq.orderBy(cb.asc(root.get("createTime")));
                return null;
            }
        }, pageable);

        return res;
    }

    @Override
    public Page<MsgCustMess> getMsgCustMessIdList(Long msgCustCategorId, Pageable pageable) {
        Page<MsgCustMess> res = msgCustMessDao.findAll(new Specification<MsgCustMess>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<MsgCustMess> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                Path<Long> msgCustCategoryId = root.get("msgCustCategoryId");
                List<Predicate> list = new ArrayList<>();

                list.add(cb.equal(msgCustCategoryId, msgCustCategorId));

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                cq.orderBy(cb.asc(root.get("sort")));
                return null;
            }
        }, pageable);

        return res;

    }

    @Override
    public Page<MsgCustMess> findByCondition( Pageable pageable) {
        User u = securityUtil.getCurrUser();
        Page<MsgCustMess> res = msgCustMessDao.findAll(new Specification<MsgCustMess>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<MsgCustMess> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                cq.orderBy(cb.asc(root.get("sort")));
                return null;
            }
        }, pageable);
        return res;
    }

    @Override
    public void genCustMess(MsgCustMessDto msgCustMessDto) {
        MsgCustMess msgCustMess = new MsgCustMess();
        ObjectUtil.copyPropertiesIgnoreNull(msgCustMessDto, msgCustMess);
        List<User> users = userRoleService.findUserByRoleName(CommonConstant.ROLE_KEFU);
//        for (User user : users) {
//            msgCustMess.setStatus(CommonConstant.MESSAGE_STATUS_UNREAD);
//            msgCustMess.setReplayUserId(user.getId());
//            msgCustMessDao.save(msgCustMess);
//        }
    }

    @Override
    public void replayCustMess(MsgCustMessReplayDto msgCustMessDto) {
        User u = securityUtil.getCurrUser();
        MsgCustMess msgCustMess = msgCustMessDao.getOne(msgCustMessDto.getMsgId());
        if (msgCustMess != null) {
//            msgCustMess.setReplayUserId(u.getId());
            msgCustMess.setReplayMess(msgCustMessDto.getReplayMess());
//            msgCustMess.setStatus(MessStatusEnum.MESS_REPLAY.getCode());
            msgCustMessDao.save(msgCustMess);
        } else {
            throw new FreightException("请选择正确的客诉消息");
        }

    }

}